package com.example.javaproject;

public class ByteArrayHexString {
    public static final String HEX = "0123456789abcdef";

    public static void main(String[] args) {
        final byte[] source = "Hello,World|".getBytes();
        final String hexString = byteArray2HexString(source);
        System.out.println(hexString);

        final byte[] bytes = hexString2ByteArray(hexString);
        System.out.println(bytes.length == source.length);
        for (int i = 0; i < source.length; i++) {
            if (bytes[i] != source[i]) {
                System.out.println("not eques");
                break;
            }
        }
        System.out.println(new String(bytes));
    }

    public static byte[] hexString2ByteArray(String hexString) {
        if (hexString == null) return null;
        final byte[] bytes = new byte[hexString.length() >> 1];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ((Character.digit(hexString.charAt(2 * i), 16) << 4) + Character.digit(hexString.charAt(2 * i + 1), 16));
        }
        return bytes;
    }


    public static String byteArray2HexString(byte[] bytes) {
        if (bytes == null || bytes.length == 0) return null;

        StringBuilder stringBuilder = new StringBuilder(bytes.length << 1);
        for (byte b : bytes) {
            final int i = b & 0xff;
            if(i<16) stringBuilder.append('0');
            stringBuilder.append(Integer.toHexString(i));
        }
        return stringBuilder.toString();
    }
}
